package com.itggm.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.itggm.Result.ResponseResult;
import com.itggm.mapper.MailMapper;
import com.itggm.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author: ggm
 * @data 2024年12月20日 16:35
 */
@Service
public class MailServiceImpl implements MailService {
    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String account;

    @Autowired
    private MailMapper mailMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public ResponseResult sendMessage(String emailAddress) {
        //创建邮箱对象
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 接收人
        simpleMailMessage.setTo(emailAddress);
        // 发送人
        simpleMailMessage.setFrom(account);
        // 设置邮件摘要
        simpleMailMessage.setSubject("你的验证码为");
        // 邮件发送日期
        simpleMailMessage.setSentDate(new Date());
        // 邮件内容   code
        //随机生成6位数作为验证码
        int code = RandomUtil.randomInt(100000, 999999);
        simpleMailMessage.setText("[数智教育平台]您的验证码是:"+code+",三分钟有效...");
        //将验证码存入redis
        stringRedisTemplate.opsForValue().set(emailAddress,""+code,3, TimeUnit.MINUTES);
        //发送邮箱验证码
        javaMailSender.send(simpleMailMessage);
        return ResponseResult.success().message("验证码发送成功");
    }
}
